//---------------------------------------------------------------------------------
// Copyright (c) 2011, Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//---------------------------------------------------------------------------------

namespace Microsoft.Samples.ServiceBus.WindowsPhoneChat.Commands
{
    using System;
    using Microsoft.Samples.ServiceBus.Messaging;
    using Microsoft.Samples.ServiceBus.WindowsPhoneChat.ViewModels;

    public class SubscribeToTopicCommand : Command<ChatTopicViewModel>
    {
        protected override bool CanExecute(ChatTopicViewModel viewModel)
        {
            return viewModel != null;
        }

        protected override void Execute(ChatTopicViewModel viewModel)
        {
            // Add/Remove a subscription using the current user's name
            var subscriptionName = App.Context.UserName;

            // If currently subscribed, begin a request to unsubscribe from the topic, if currently
            // unsubscribed, begin a request to subscribe. Pass the Topic's view model as the Async
            // state so that the view can be updated when the call completes
            if (viewModel.IsSubscribed)
            {
                viewModel.TopicClient.BeginRemoveSubscription(subscriptionName, this.OnRemoveSubscriptionCompleted, viewModel);
            }
            else
            {
                viewModel.TopicClient.BeginAddSubscription(subscriptionName, new SubscriptionDescription(), this.OnAddSubscriptionCompleted, viewModel);
            }
        }

        private void OnRemoveSubscriptionCompleted(IAsyncResult result)
        {
            // Retrieve the topic's view model from the async state
            var viewModel = (ChatTopicViewModel)result.AsyncState;

            try
            {
                // end the async call to remove subscription - if the call failed, an exception will
                // be thrown
                viewModel.TopicClient.EndRemoveSubscription(result);

                // update the view model to indicate that there is no longer an active subscription
                // to this topic - this will result in the 'star' next to the topic becoming greyed
                // out and receives on the subscription to end
                viewModel.Dispatcher.BeginInvoke(() => viewModel.SubscriptionClient = null);
            }
            catch (Exception e)
            {
                App.ShowError(e);
            }
        }

        private void OnAddSubscriptionCompleted(IAsyncResult result)
        {
            // Retrieve the topic's view model from the async state
            var viewModel = (ChatTopicViewModel)result.AsyncState;

            try
            {
                // end the async call to add a subscription - if the call failed, an exception will
                // be thrown
                var subscriptionClient = viewModel.TopicClient.EndAddSubscription(result);

                // update the view model to indicate that there is an active subscription to this 
                // topic - this will result in the 'star' next to the topic becoming highlighted
                // and receives on the subscription to begin if this topic is currently selected
                viewModel.Dispatcher.BeginInvoke(() => viewModel.SubscriptionClient = subscriptionClient);
            }
            catch (Exception e)
            {
                App.ShowError(e);
            }
        }
    }
}
